package com.jiexinyun.security;

import com.jiexinyun.constants.ConstantsC;
import com.jiexinyun.utils.CommonUtils;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("ss")
public class PermissionService {
    /**
     * 验证用户是否具备某权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission) {
        if (CommonUtils.isEmpty(permission)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (CommonUtils.isNull(loginUser) || CommonUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }
        PermissionContextHolder.setContext(permission);
        return hasPermissions(loginUser.getPermissions(), permission);
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 以 PERMISSION_DELIMETER 为分隔符的权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyPermi(String permissions) {
        if (CommonUtils.isEmpty(permissions)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (CommonUtils.isNull(loginUser) ||
                CommonUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }
        PermissionContextHolder.setContext(permissions);
        List<String> authorities = loginUser.getPermissions();
        for (String permission : permissions.split(ConstantsC.PERMISSION_DELIMETER)) {
            if (permission != null &&
                    hasPermissions(authorities, permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     * 
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(List<String> permissions, String permission) {
        return permissions.contains(ConstantsC.ALL_PERMISSION) ||
                permissions.contains(CommonUtils.trim(permission));
    }

}
